<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <!-- 添加角色按钮 -->
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['btborder', i1 === 0 ? 'topborder' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="['vcenter', i2 === 0 ? '' : 'topborder']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 角色列表区域 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini"
            >删除</el-button
          >
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)" 
            >分配权限</el-button
          >
            </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible='setRightsDialogVisible'
      @close="closeSetRightsDialog"
    >
        <!-- props绑定显示数据, node-key每个节点的唯一标识属性  default-expand-all默认全部展开 default-checked-keys默认勾选数组-->
          <el-tree :data="rightsList" :props="treeProps"  node-key="id" default-expand-all show-checkbox :default-checked-keys="defKeys" ref="treeRef"></el-tree>
          <span slot="footer" class="dialog-footer">
        <el-button @click="closeSetRightsDialog">取 消</el-button>
        <el-button type="primary" @click="confirmSubmitRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [], //角色列表数据
      rightsList: [], //所有权限
      treeProps:{
          label:'authName',
          children:'children',
      },//树形控件绑定对象
      setRightsDialogVisible : false,   
      roleId:'',//保存分配权限的角色id
      defKeys:[],//保存选中角色的已有权限的id

    }
  },
  created() {
    this.getrolesList()
  },
  methods: {
    async getrolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status != 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 删除指定id的权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('权限删除失败')
      }
      role.children = res.data
    },
    async showSetRightsDialog(role){
        this.roleId = role.id //保存选中的角色ID,后面提交分配用
        //获取树形权限列表(接口只提供所有)
        const{data:res} = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) {
            this.$message.error('获取权限数据失败')}
        this.rightsList = res.data
        //defKeys数组保存选中角色的权限id
            this.getLeafKey(role)
        //打开分配权限对话框
        this.setRightsDialogVisible = true
       
        
    },
    //利用递归函数获取三级节点id
    getLeafKey(role){
        if (!role.children) {
            return this.defKeys.push(role.id)
        }
        //不是三级节点,调用递归
        role.children.forEach(item =>this.getLeafKey(item));

    },
    //点击确认后提交分配权限
    async confirmSubmitRights(){
        const keys=[...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedNodes()]//获取选中和半选中节点
        //keys数组转化为字符串,作为请求参数
        const strKeys = keys.join(',')
        const{data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:strKeys})
        if (res.meta.status!==200) {
            this.$message.error("分配权限失败!")
        }
        this.$message.success("分配权限成功!")
        this.getrolesList()
        this.setRightsDialogVisible = false
    },
    //关闭或取消对话框
    closeSetRightsDialog(){
        this.defKeys=[]
        this.setRightsDialogVisible = false
    }
  },
}
</script>
<style scoped>
.btborder {
  border-bottom: 1px solid #eee;
}
.topborder {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 6px;
}
</style>